﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CH.Easy.UI.Domain;
using System.Web;
using CH.Easy.Ioc;
using CH.Easy.UI.Common;
using CH.Easy.UI.PageAgg;
using CH.Easy.UI.Domain.ModuleAgg;

namespace CH.Easy.UI.Domain.PageAgg
{
    public class LayoutPosition
    {
        string paramPattern = @"(?<Name>name|id)=(?<Value>\S+)";
        public Dictionary<string, string> Parameters = new Dictionary<string, string>();
        public List<BaseModule> Modules = new List<BaseModule>();
        public StringBuilder Template = new StringBuilder();
        public int ID
        {
            get
            {
                try
                {
                    return this.Parameters["id"].ToInt();
                }
                catch
                {

                    return 0;
                }
            }
        }
        public LayoutPosition(string label, BasePage page)
        {

            try
            {
                //初始化当前位置的参数信息
                Regex r = new Regex(paramPattern, RegexOptions.IgnoreCase);
                MatchCollection mc = r.Matches(label);
                foreach (Match item in mc)
                {
                    Parameters.Add(item.Groups["Name"].Value, item.Groups["Value"].Value.RegexReplace("\"", ""));
                }
                //加载当前位置 所拥有的模块
                var pageRepository = IocContainer.Resolve<IPageRepository>();
                var moduleRepository = IocContainer.Resolve<IModuleRepository>();

                List<PagePositionModule> PagePositionModuleList = pageRepository.GetModuleList(page.ID, this.ID);
                foreach (PagePositionModule pagePositionModule in PagePositionModuleList)
                {
                    //加载模块配置信息
                    BaseModule am = moduleRepository.GetByFilter(p => p.ID == pagePositionModule.ID);
                    BaseModule module = am.Create(page);
                    //准备初始化模块
                    module.PreInit();
                    //初始化模块
                    module.Init();
                    //设置模块的数据
                    module.SetDataSource();
                    //加载模块的模板信息
                    Template.Append(module.GetTemplate());

                }
            }
            catch (Exception ex)
            {
                Template.Clear();
                Template.Append(ex.ToString());
            }



        }
    }
}
